/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "plugins/ecmascript/runtime/base/builtins_base.h"
#include "plugins/ecmascript/runtime/ecma_vm.h"
#include "plugins/ecmascript/runtime/global_env.h"
#include "plugins/ecmascript/runtime/internal_call_params.h"
#include "plugins/ecmascript/runtime/js_invoker.h"
#include "plugins/ecmascript/runtime/js_map.h"
#include "plugins/ecmascript/runtime/js_map_iterator.h"
#include "plugins/ecmascript/runtime/base/object_helper.h"
#include "plugins/ecmascript/runtime/linked_hash_table.h"
#include "plugins/ecmascript/runtime/object_factory.h"

namespace ark::ecmascript::builtins {
// 23.1.1.1
JSTaggedValue map::MapConstructor(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), Map, MapConstructor);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
    // 1.If NewTarget is undefined, throw a TypeError exception
    JSHandle<JSTaggedValue> newTarget = builtins_common::GetNewTarget(argv);
    if (newTarget->IsUndefined()) {
        // throw type error
        THROW_TYPE_ERROR_AND_RETURN(thread, "new target can't be undefined", JSTaggedValue::Exception());
    }
    // 2.Let Map be OrdinaryCreateFromConstructor(NewTarget, "%MapPrototype%", «‍[[MapData]]» ).
    JSHandle<JSTaggedValue> constructor = builtins_common::GetConstructor(argv);
    JSHandle<JSObject> obj = factory->NewJSObjectByConstructor(JSHandle<JSFunction>(constructor), newTarget);
    // 3.returnIfAbrupt()
    RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
    JSHandle<JSMap> map = JSHandle<JSMap>::Cast(obj);

    // 4.Set map’s [[MapData]] internal slot to a new empty List.
    JSHandle<LinkedHashMap> linkedMap = LinkedHashMap::Create(thread);
    map->SetLinkedMap(thread, linkedMap);
    // add data into set from iterable
    // 5.If iterable is not present, let iterable be undefined.
    // 6.If iterable is either undefined or null, let iter be undefined.
    JSHandle<JSTaggedValue> iterable = builtins_common::GetCallArg(argv, 0);
    // 8.If iter is undefined, return set
    if (iterable->IsUndefined() || iterable->IsNull()) {
        return map.GetTaggedValue();
    }
    if (!iterable->IsECMAObject()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "iterable is not object", JSTaggedValue::Exception());
    }
    // Let adder be Get(map, "set").
    JSHandle<JSTaggedValue> adderKey(factory->NewFromCanBeCompressString("set"));
    JSHandle<JSTaggedValue> adder = JSObject::GetProperty(thread, JSHandle<JSTaggedValue>(map), adderKey).GetValue();
    // ReturnIfAbrupt(adder).
    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, adder.GetTaggedValue());
    JSTaggedValue result =
        base::ObjectHelper::AddEntriesFromIterable(thread, JSHandle<JSTaggedValue>(map), iterable, adder);
    RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, result);
    return result;
}

// 23.1.3.9
JSTaggedValue map::proto::Set(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Set);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);

    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }

    JSHandle<JSTaggedValue> key = builtins_common::GetCallArg(argv, 0);
    JSHandle<JSTaggedValue> value = builtins_common::GetCallArg(argv, 1);

    JSHandle<JSMap> map(self);
    JSMap::Set(thread, map, key, value);
    return map.GetTaggedValue();
}

// 23.1.3.1
JSTaggedValue map::proto::Clear(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Clear);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);

    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);

    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }
    JSHandle<JSMap> map(self);
    JSMap::Clear(thread, map);
    return JSTaggedValue::Undefined();
}

// 23.1.3.3
JSTaggedValue map::proto::Delete(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Delete);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);
    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }

    JSHandle<JSMap> map(self);
    JSHandle<JSTaggedValue> key = builtins_common::GetCallArg(argv, 0);
    bool flag = JSMap::Delete(thread, map, key);
    return builtins_common::GetTaggedBoolean(flag);
}

// 23.1.3.7
JSTaggedValue map::proto::Has(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Has);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self(builtins_common::GetThis(argv));
    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }
    JSHandle<JSMap> jsMap(thread, JSMap::Cast(*JSTaggedValue::ToObject(thread, self)));
    JSHandle<JSTaggedValue> key = builtins_common::GetCallArg(argv, 0);
    bool flag = false;
    if (JSMap::IsKey(key.GetTaggedValue())) {
        int hash = LinkedHash::Hash(key.GetTaggedValue());
        flag = jsMap->Has(key.GetTaggedValue(), hash);
    }
    return builtins_common::GetTaggedBoolean(flag);
}

// 23.1.3.6
JSTaggedValue map::proto::Get(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Get);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self(builtins_common::GetThis(argv));
    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }
    JSHandle<JSMap> jsMap(thread, JSMap::Cast(*JSTaggedValue::ToObject(thread, self)));
    JSHandle<JSTaggedValue> key = builtins_common::GetCallArg(argv, 0);
    JSTaggedValue value = JSTaggedValue::Undefined();
    if (JSMap::IsKey(key.GetTaggedValue())) {
        int hash = LinkedHash::Hash(key.GetTaggedValue());
        value = jsMap->Get(key.GetTaggedValue(), hash);
    }
    return value;
}

// 23.1.3.5
JSTaggedValue map::proto::ForEach([[maybe_unused]] EcmaRuntimeCallInfo *argv)
{
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);
    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }
    JSHandle<JSMap> map(thread, JSMap::Cast(*JSTaggedValue::ToObject(thread, self)));

    // 4.If IsCallable(callbackfn) is false, throw a TypeError exception.
    JSHandle<JSTaggedValue> func(builtins_common::GetCallArg(argv, 0));
    if (!func->IsCallable()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not Callable", JSTaggedValue::Exception());
    }
    // 5.If thisArg was supplied, let T be thisArg; else let T be undefined.
    JSHandle<JSTaggedValue> thisArg = builtins_common::GetCallArg(argv, 1);

    // composed arguments
    JSHandle<JSTaggedValue> iter(factory->NewJSMapIterator(map, IterationKind::KEY_AND_VALUE));
    JSHandle<JSTaggedValue> keyIndex(thread, JSTaggedValue(0));
    JSHandle<JSTaggedValue> valueIndex(thread, JSTaggedValue(1));
    JSHandle<JSTaggedValue> result = JSIterator::IteratorStep(thread, iter);

    while (!result->IsFalse()) {
        RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, result.GetTaggedValue());
        JSHandle<JSTaggedValue> iterValue(JSIterator::IteratorValue(thread, result));
        JSHandle<JSTaggedValue> key = JSObject::GetProperty(thread, iterValue, keyIndex).GetValue();
        JSHandle<JSTaggedValue> value = JSObject::GetProperty(thread, iterValue, valueIndex).GetValue();
        // Let funcResult be Call(callbackfn, T, «e, e, S»).
        auto info = NewRuntimeCallInfo(thread, func, thisArg, JSTaggedValue::Undefined(), 3);
        info->SetCallArgs(value, key, JSHandle<JSTaggedValue>(map));
        JSTaggedValue ret = JSFunction::Call(info.Get());  // 3: three args
        // returnIfAbrupt
        RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, ret);
        result = JSIterator::IteratorStep(thread, iter);
    }

    return JSTaggedValue::Undefined();
}

// 23.1.2.2
JSTaggedValue map::GetSpecies([[maybe_unused]] EcmaRuntimeCallInfo *argv)
{
    return builtins_common::GetThis(argv).GetTaggedValue();
}

// 23.1.3.10
JSTaggedValue map::proto::GetSize(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, GetSize);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self(builtins_common::GetThis(argv));
    // 2.If Type(S) is not Object, throw a TypeError exception.
    // 3.If S does not have a [[MapData]] internal slot, throw a TypeError exception.
    if (!self->IsJSMap()) {
        THROW_TYPE_ERROR_AND_RETURN(thread, "obj is not JSMap", JSTaggedValue::Exception());
    }
    JSMap *jsMap = JSMap::Cast(*JSTaggedValue::ToObject(thread, self));
    int count = jsMap->GetSize();
    return JSTaggedValue(count);
}

// 23.1.3.4
JSTaggedValue map::proto::Entries(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Entries);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);
    JSHandle<JSTaggedValue> iter = JSMapIterator::CreateMapIterator(thread, self, IterationKind::KEY_AND_VALUE);
    return iter.GetTaggedValue();
}

// 23.1.3.8
JSTaggedValue map::proto::Keys(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Keys);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);
    JSHandle<JSTaggedValue> iter = JSMapIterator::CreateMapIterator(thread, self, IterationKind::KEY);
    return iter.GetTaggedValue();
}

// 23.1.3.11
JSTaggedValue map::proto::Values(EcmaRuntimeCallInfo *argv)
{
    BUILTINS_API_TRACE(argv->GetThread(), MapPrototype, Values);
    JSThread *thread = argv->GetThread();
    [[maybe_unused]] EcmaHandleScope handleScope(thread);
    JSHandle<JSTaggedValue> self = builtins_common::GetThis(argv);
    JSHandle<JSTaggedValue> iter = JSMapIterator::CreateMapIterator(thread, self, IterationKind::VALUE);
    return iter.GetTaggedValue();
}
}  // namespace ark::ecmascript::builtins
